<template>
  <div class="file-page">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="文件转文字" name="first"></el-tab-pane>
      <el-tab-pane label="录音转文字" name="second"></el-tab-pane>
    </el-tabs>
    
      <SearchInput v-model="searchText" />
    
    <div class="file-list">
          <div
            v-for="item in fileList"
            :key="item.id"
            class="file-item-wrapper"
          >
            <div class="file-item" @click="handleFileItemClick(item)">
              <div class="file-icon">
                <img src="@/assets/images/file/fileIcon.png" alt="file" />
              </div>
              <div class="file-info">
                <div class="file-title">{{ item.title }}</div>
                <div class="file-meta">
                  <span class="duration">
                    <el-icon :size="14"><Microphone /></el-icon>
                    {{ item.duration ? item.duration : '00:00' }}
                  </span>
                  <span class="divider">|</span>
                  <span class="date">{{ item.createTime }}</span>
                  <span class="divider">|</span>
                  <span class="status" :class="statusMap[item.status]?.type || 'primary'">
                    {{
                          statusMap[item.status]
                            ? statusMap[item.status].label
                            : "处理中"
                        }}
                  </span>
                </div> 
              </div>
              <div class="file-actions">
                <el-icon :size="16" color="#9C9C9C">
                  <MoreFilled />
                </el-icon>
              </div>
            </div>
            
            <!-- 操作菜单 - 在文件项下方展开 -->
            <div v-if="currentFile?.id === item.id" class="action-menu" @click.stop>
              <div class="action-menu-item" @click.stop="handleDelete">
                <img src="@/assets/images/file/delete.png" alt="delete" />
                <span>删除</span>
              </div>
              <div class="action-menu-item" @click.stop="handleDownload">
                <img src="@/assets/images/file/download.png" alt="download" />
                <span>下载</span>
              </div>
              <div class="action-menu-item" @click.stop="handleEdit">
                <img src="@/assets/images/file/edit.png" alt="edit" />
                <span>编辑</span>
              </div>
            </div>
          </div>
        
        <!-- 加载提示 -->
        <div v-if="loading" class="loading-tip">
          <el-icon class="is-loading" :size="20"  v-if="loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        
        <!-- 无更多数据提示 -->
        <div v-if="!loading && noMoreData && fileList.length === 0" class="no-more-tip">暂无数据</div>
        
        <!-- 已加载完所有数据提示 -->
        <div v-if="!loading && noMoreData && fileList.length > 0" class="all-loaded-tip">已加载全部数据</div>
    </div>

    <Navigation />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import Navigation from "@/components/navigation/index.vue";
import SearchInput from "@/components/search/index.vue";
import {
  Document,
  Microphone,
  MoreFilled,
  Delete,
  Download,
  Edit,
  Loading,
} from "@element-plus/icons-vue";
import { getFileList, deleteFile } from "@/api/file";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from 'vue-router'
const router = useRouter()
// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(20);
const totalCount = ref(0);
const loading = ref(false);
const noMoreData = ref(false);
const currentType = ref(0); // 当前 tab 的 type：0-导入文件转文字，1-录音实时转文字


const getFileListData = async (isLoadMore = false) => {
  // 如果正在加载或已经没有更多数据，直接返回
  if (loading.value || (noMoreData.value && isLoadMore)) {
    return;
  }
  
  loading.value = true;
  
  try {
    const res = await getFileList({
      page: currentPage.value,
      pageSize: pageSize.value,
      category: 1,
      type: currentType.value, // 添加 type 参数
      title: searchText.value, // 添加搜索关键词参数
    });
    
    if (res.code === 1 && res.data ) {

      totalCount.value = res.data.total;
      
      if (isLoadMore) {
        // 加载更多时，累积数据
        fileList.value = [...fileList.value, ...res.data.records];
      } else {
        // 首次加载时，直接赋值
        fileList.value = res.data.records;
      }
      
      // 判断是否已加载完所有数据
      if (fileList.value.length >= totalCount.value || totalCount.value === 0) {
        noMoreData.value = true;
      }
    } else {
      // 接口返回失败，也需要设置 noMoreData 为 true，这样才能显示"暂无数据"
      noMoreData.value = true;
      ElMessage.error('获取文件列表失败');
    }
  } catch (error) {
    console.error('获取文件列表失败:', error);
    // 接口异常时，也需要设置 noMoreData 为 true
    noMoreData.value = true;
    ElMessage.error('获取文件列表失败');
  } finally {
    loading.value = false;
  }
};

const statusMap: Record<number, { label: string; type: string }> = {
  0: { label: "处理中", type: "primary" },
  1: { label: "转写完成", type: "info" },
  2: { label: "已完成", type: "success" },
  '-1': { label: "转写失败", type: "danger" },
  '-2': { label: "生成失败", type: "danger" },
};

interface FileItem {
  id: number;
  title: string;
  duration: string;
  status: number;
  createTime: string;
}

const activeName = ref("first");
const searchText = ref("");
const currentFile = ref<FileItem | null>(null);

// 导入文件转文字列表数据
const fileList = ref<FileItem[]>([]);


// 监听搜索文本变化
watch(searchText, () => {
  currentPage.value = 1;
  noMoreData.value = false;
  fileList.value = [];
  getFileListData(false); // 传递 false 表示不是加载更多，而是重新加载
});

const handleClick = (tab: any, event: any) => {
  currentPage.value = 1;
  noMoreData.value = false;
  fileList.value = []; // 清空当前列表
  console.log(fileList.value,'123123');
  
  if(tab.paneName === 'first') {
    currentType.value = 0; // 导入文件转文字
    getFileListData(false); // 传递 false 表示不是加载更多
  } else if(tab.paneName === 'second') {
    currentType.value = 1; // 录音实时转文字
    getFileListData(false); // 传递 false 表示不是加载更多
  }
};

const handleFileClick = (item: FileItem) => {
  console.log("点击文件:", item);
  // 可以在这里实现跳转到详情页等逻辑
};

const handleFileItemClick = (item: FileItem) => {
  // 如果点击的是已展开菜单的文件项，则关闭菜单
  if (currentFile.value?.id === item.id) {
    currentFile.value = null;
  } else {
    // 否则打开该文件项的菜单（会自动关闭其他已打开的菜单）
    currentFile.value = item;
  }
};

const handleDelete = async () => {
  if (!currentFile.value) return;
  
  // 弹出确认对话框
  ElMessageBox.confirm(
    '确定要删除这个文件吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 调用删除接口
      const res = await deleteFile({ id: currentFile.value!.id });
      
      if (res.code === 1) {
        ElMessage.success('删除成功');
        
        // 关闭操作菜单
        currentFile.value = null;
        
        // 重新加载列表
        currentPage.value = 1;
        noMoreData.value = false;
        fileList.value = [];
        getFileListData(false);
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      ElMessage.error('删除失败');
    }
  })
  .catch(() => {
    // 用户点击取消，不做任何操作
  });
};

const handleDownload = () => {
  console.log("下载", currentFile.value);
  // 实现下载逻辑
  // 注意：操作菜单不关闭，需要点击文件项才关闭
};

const handleEdit = () => {
  console.log("编辑", currentFile.value);
  // 实现编辑逻辑
  // 注意：操作菜单不关闭，需要点击文件项才关闭
  router.push({ path: "/fileEdit", query: { id: currentFile.value?.id?.toString(), type : currentType.value } });
};


// 滚动加载更多
const handleScroll = () => {
  // 获取滚动位置
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  const clientHeight = document.documentElement.clientHeight || window.innerHeight;
  
  // 当滚动到距离底部200px时触发加载
  if (scrollTop + clientHeight >= scrollHeight - 200) {
    // 如果还有更多数据，加载下一页
    if (!noMoreData.value && !loading.value) {
      currentPage.value++;
      getFileListData(true);
    }
  }
};

onMounted(() => {
  // 检查URL参数，设置正确的tab
  const route = router.currentRoute.value;
  const activeNameParam = route.query.activeName;
  
  if (activeNameParam === 'second') {
    activeName.value = 'second';
    currentType.value = 1; // 录音实时转文字
  } else {
    activeName.value = 'first';
    currentType.value = 0; // 导入文件转文字
  }
  
  getFileListData(false); // 首次加载，传递 false
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style lang="scss" scoped>
.file-page {
  padding-bottom: 80px; // 为底部导航留出空间
  background-color: #ffffff;
  min-height: 100vh;
}

:deep(.demo-tabs) {
  position: sticky;
  top: 0;
  z-index: 99;
  background-color: #fff;

  .el-tabs__header {
    margin: 0;
    font-size: 16px;
    background-color: #fff;
  }

  .el-tabs__nav {
    width: 100%;
    display: flex;
  }

  .el-tabs__item {
    flex: 1;
    font-size: 16px;
    text-align: center;
    padding: 0 25px;
    height: 60px;
    line-height: 60px;
  }
}

.file-list {
  background-color: #fff;
}

.file-item-wrapper {
  border-bottom: 1px solid #f0f0f0;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  cursor: pointer;
  transition: background-color 0.2s;

  &:active {
    background-color: #f8f8f8;
  }
  
  .file-item-wrapper:has(.action-menu) & {
    background-color: #F6FAFF;
  }
}

.file-icon {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  img {
    width: 100%;
    height: 100%;
  }
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #999;

  .duration {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .divider {
    margin: 0 8px;
  }

  .status {
    font-weight: 500;

    &.primary {
      color: #1890ff; // 处理中 - 蓝色
    }

    &.info {
      color: #909399; // 转写完成 - 灰色
    }

    &.success {
      color: #52c41a; // 已完成 - 绿色
    }

    &.danger {
      color: #ff4d4f; // 失败 - 红色
    }
  }
}

.file-actions {
  flex-shrink: 0;
  padding-left: 12px;
  transform: rotate(90deg);
}

// 操作菜单 - 在文件项下方展开
.action-menu {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #F6FAFF;
  padding-bottom: 10px;
}

.action-menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 20px;
  transition: opacity 0.2s;

  &:active {
    opacity: 0.6;
  }

  span {
    font-size: 14px;
    color: #333;
  }

  img{
    width:23px;
  }
}

// 加载提示和无数据提示
.loading-tip,
.no-more-tip,
.all-loaded-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 20px;
  font-size: 14px;
  color: #999;
  background-color: #fff;
  gap: 5px;
}

.loading-tip {
  color: #1890ff;
}

.all-loaded-tip {
  color: #ccc;
  font-size: 12px;
}

</style>
